package hivi.vn.hivigold.activities;

import java.io.File;

import hivi.vn.hivigold.R;
import hivi.vn.hivigold.database.WebService;
import hivi.vn.hivigold.objects.Partner;
import hivi.vn.hivigold.utils.Formats;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class PartnerEditor extends Activity {
	Partner p;
	public static final String ACTION_KEY = "ACTION";
	public static final int ACTION_NEW = 1;
	public static final int ACTION_EDIT = 2;
	public static final String DATA_REFERENCE = "PARTNER";
	public static final int TAKE_PICTURE = 1;
	public static final int CHOOSE_PICTURE = 2;
	public int CURRENT_ACTION;

	ImageButton imgPartner;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.partner_editor);

		Button btnSave = (Button) findViewById(R.id.btnSave);
		Button btnCancel = (Button) findViewById(R.id.btnCancel);
		final EditText txtPartnerID = (EditText) findViewById(R.id.txtPartnerID);
		final EditText txtPartnerName = (EditText) findViewById(R.id.txtPartnerName);
		final EditText txtPartnerAdd = (EditText) findViewById(R.id.txtPartnerAdd);
		final EditText txtPartnerTel = (EditText) findViewById(R.id.txtPartnerTel);
		final EditText txtPartnerMail = (EditText) findViewById(R.id.txtPartnerEmail);
		final EditText txtPartnerNote = (EditText) findViewById(R.id.txtPartnerNote);
		imgPartner = (ImageButton) findViewById(R.id.imgPartner);

		Bundle b = this.getIntent().getExtras();
		CURRENT_ACTION = b.getInt(ACTION_KEY);
		if (CURRENT_ACTION == ACTION_EDIT) {
			p = (Partner) b.getSerializable(DATA_REFERENCE);
			txtPartnerID.setEnabled(false);
			txtPartnerID.setText(p.getPartnerID());
			txtPartnerName.setText(p.getPartnerName());
			txtPartnerAdd.setText(p.getPartnerAddress());
			txtPartnerNote.setText(p.getPartnerNote());
			txtPartnerTel.setText(p.getPartnerTel());
			txtPartnerMail.setText(p.getPartnerMail());
			imgPartner.setTag(p.getPartnerImage());
			Bitmap bm = Formats.creatBitmap(p.getPartnerImage());
			if (bm != null) {
				imgPartner.setImageBitmap(bm);
			}
		}

		btnSave.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (txtPartnerID.getText().toString().trim().length() == 0
						|| txtPartnerName.getText().toString().trim().length() == 0) {
					Toast.makeText(getBaseContext(),
							R.string.warning_notempty,
							Toast.LENGTH_LONG).show();
					return;
				}
				if (CURRENT_ACTION == ACTION_NEW) {
					if (WebService.checkPartnerID(getBaseContext(),
							txtPartnerID.getText().toString().trim())) {
						Toast.makeText(getBaseContext(),
								R.string.warning_partner_already_exist,
								Toast.LENGTH_LONG).show();
						return;
					} else {
						p = new Partner();
						p.setPartnerID(txtPartnerID.getText().toString().trim());
					}
				}
				p.setPartnerName(txtPartnerName.getText().toString().trim());
				p.setPartnerAddress(txtPartnerAdd.getText().toString().trim());
				p.setPartnerTel(txtPartnerTel.getText().toString().trim());
				p.setPartnerMail(txtPartnerMail.getText().toString().trim());
				p.setPartnerNote(txtPartnerNote.getText().toString().trim());
				p.setPartnerImage(imgPartner.getTag()!=null?imgPartner.getTag().toString():"");
				PartnerTask pt = new PartnerTask();
				pt.execute(p);
			}
		});

		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				setResult(RESULT_CANCELED);
				finish();
			}
		});

		imgPartner.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				AlertDialog.Builder builder = new AlertDialog.Builder(PartnerEditor.this);
				builder.setTitle(R.string.choose);
				builder.setItems(R.array.image_option,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								whenChooseOptionImage(which);
							}
						});
				AlertDialog alert = builder.create();
				alert.show();
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case CHOOSE_PICTURE:
				String path = "";
				Uri selectImage = data.getData();
				String[] projection = { MediaStore.Images.Media.DATA };
				Cursor cursor = getContentResolver().query(selectImage,
						projection, null, null, null);
				if (cursor != null) {
					if (cursor.moveToFirst()) {
						path = cursor.getString(cursor
								.getColumnIndex(projection[0]));
						File f = new File(path);
						if (f.exists()) {
							Bitmap bm = Formats.creatBitmap(f.getPath());
							if (bm != null) {
								imgPartner.setImageBitmap(bm);
								imgPartner.setTag(f.getPath());
							} else {
								imgPartner.setImageResource(R.drawable.nophoto);
								imgPartner.setTag("");
							}
						}
					}
				}
				break;
			case TAKE_PICTURE:
				if (imgPartner.getTag() != null) {
					File f = new File(imgPartner.getTag().toString());
					if (f.exists()) {
						Bitmap bm = Formats.creatBitmap(f.getPath());
						if (bm != null) {
							imgPartner.setImageBitmap(bm);
							imgPartner.setTag(f.getPath());
						} else {
							imgPartner.setImageResource(R.drawable.nophoto);
							imgPartner.setTag("");
						}
					}
				}
				break;
			}
		}
	}

	private void whenChooseOptionImage(int position) {
		switch (position) {
		case 0:
			Intent i = new Intent(Intent.ACTION_PICK,
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(i, CHOOSE_PICTURE);
			break;
		case 1:
			Intent i1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			File f = new File(Environment.getExternalStorageDirectory(),
					String.valueOf(System.currentTimeMillis()) + ".jpg");
			i1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
			imgPartner.setTag(f.getPath());
			startActivityForResult(i1, TAKE_PICTURE);
			break;
		}
	}

	private class PartnerTask extends AsyncTask<Partner, Void, Boolean> {
		ProgressDialog dialog;

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result) {
				Toast.makeText(
						getBaseContext(),
						CURRENT_ACTION == ACTION_NEW ? R.string.alert_add_partner_success
								: R.string.alert_edit_partner_success,
						Toast.LENGTH_LONG).show();
				setResult(RESULT_OK);
				finish();
			} else {
				Toast.makeText(
						getBaseContext(),
						CURRENT_ACTION == ACTION_NEW ? R.string.alert_add_partner_success
								: R.string.alert_add_partner_error,
						Toast.LENGTH_LONG).show();
			}
			dialog.dismiss();
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog = new ProgressDialog(PartnerEditor.this);
			dialog.setMessage(getResources().getString(R.string.alert_waiting));
			dialog.show();
		}

		@Override
		protected Boolean doInBackground(Partner... p) {
			// TODO Auto-generated method stub
			if (CURRENT_ACTION == ACTION_NEW) {
				return WebService.insertPartner(getBaseContext(), p[0]);
			}
			return WebService.updatePartner(getBaseContext(), p[0]);
		}
	}
}
